const http = require('http');
const mysql = require('mysql');
const fs = require('fs');
const url = require('url');
const zlib = require('zlib');
const crypto = require('crypto');

const _key = 'dsuakjgfjshakdfksdfbasdhjguieywqfb8923w98ry23hdfukjwebkjbfckjdsfbjksd';

function md5(str) {
	let obj = crypto.createHash('md5');
	obj.update(str);
	return obj.digest('hex');
}

function md5_2(str) {
	return md5(md5(str) + _key);
}

let db = mysql.createPool({host: 'localhost', user: 'root', password: '', port: 3306, database: '20180131'});

// 隐患？
let server = http.createServer((request, response) => {
	let {pathname, query} = url.parse(request.url, true);
	let {user, password} = query;

	switch (pathname) {
		case '/reg':
			// 校验
			if (!user) {
				response.write('{"err": 1, "msg": "用户名不能为空"}');
				response.end();
			} else if (!password) {
				response.write('{"err": 1, "msg": "密码不能为空"}');
				response.end();
			} else if (!/^\w{4,16}$/.test(user)) {
				response.write('{"err": 1, "msg": "用户名不合法"}');
				response.end();
			} else if (/['|"]/g.test(password)) {
				response.write('{"err": 1, "msg": "密码不合法"}');
				response.end();
			} else {
				db.query(`SELECT * FROM user_table WHERE username='${user}'`, (err, data) => {
					if (err) {
						response.write('{"err": 1, "msg": "数据库错误"}')
						response.end();
					} else if (data.length > 0) {
						response.write('{"err": 1, "msg": "用户名重复"}')
						response.end();
					} else {
						db.query(`INSERT INTO user_table (ID, username, password) VALUES(0, '${user}', '${md5_2(password)}')`, (err, data) => {
							if (err) {
								response.write('{"err": 1, "msg": "数据库错误"}')
								response.end();
							} else {
								response.write('{"err": 0, "msg": "注册成功"}')
								response.end();
							}
						})
					}
				})
			}
			break;
		case '/login':
			if (!user) {
				response.write('{"err": 1, "msg": "用户名不能为空"}');
				response.end();
			} else if (!password) {
				response.write('{"err": 1, "msg": "密码不能为空"}');
				response.end();
			} else if (!/^\w{4,16}$/.test(user)) {
				response.write('{"err": 1, "msg": "用户名不合法"}');
				response.end();
			} else if (/['|"]/g.test(password)) {
				response.write('{"err": 1, "msg": "密码不合法"}');
				response.end();
			} else {
				db.query(`SELECT * FROM user_table WHERE username = '${user}'`, (err, data) => {
					if (err) {
						response.write('{"err": 1, "msg": "数据库错误"}');
						response.end();
					} else if (data[0].password != md5_2(password)) {
						response.write('{"err": 1, "msg": "用户名或密码错误"}');
						response.end();
					} else {
						response.write('{"err": 1, "msg": "登录成功"}');
						response.end();
					}

				})
			}
			break;
		default:
			let rs = fs.createReadStream(`www${pathname}`);

			let gz = zlib.createGzip();

			response.setHeader('content-encoding', 'gzip');

			rs.pipe(gz).pipe(response);

			rs.on('error', err => {
				response.writeHead(404);
				response.write('Not Found');
				response.end();
			})

	}
})

server.listen(8080);